<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4" v-if="userinfo.role == 'business' ">
          <el-button type="primary" @click="goAddpage">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 商品列表区域 -->
      <el-table :data="goodsList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#">
        </el-table-column>
				<el-table-column prop="goods_imgs" label="商品图片" width="120">
					<template slot-scope="scope">
					  <img :src=" api_url + scope.row.goods_imgs[0] " width="80px" height="80px" />
					</template>
				</el-table-column>
        <el-table-column prop="goods_name" label="商品名称">
        </el-table-column>
				<el-table-column prop="goods_msg_price" label="商品销售价格(元)" width="120">
				</el-table-column>
        <el-table-column prop="goods_price" label="商品价格(元)" width="95">
        </el-table-column>
        <el-table-column prop="goods_weight" label="商品重量" width="75">
        </el-table-column>
				<el-table-column prop="is_recommend" label="是否推荐" width="75">
					<template slot-scope="scope">
					  {{ scope.row.is_recommend ? '是' : '否' }}
					</template>
				</el-table-column>
        <el-table-column prop="add_time" label="创建时间" width="140">
          <template slot-scope="scope">
            {{ scope.row.add_time | dataFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row._id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeById(scope.row._id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum"
        :page-sizes="[10, 20, 30, 50]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper"
        :total="total" background>
      </el-pagination>

    </el-card>
		
		<!-- 修改对话框 -->
		<el-dialog title="修改商品" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
		  <!-- 内容主体区域 -->
		  <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
				<el-form-item label="商品图片" prop="goods_imgs">
					<el-upload
					  class="upload-demo"
					  :action="api_upload"
					  :on-preview="handlePreview"
						:multiple="true"
					  :on-remove="handleRemove"
						:on-success="handleAvatarSuccess"
					  :file-list="fileList"
					  list-type="picture">
					  <el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
				</el-form-item>
		    <!-- 商品名称 -->
		    <el-form-item label="商品名称" prop="goods_name">
		      <el-input v-model="editForm.goods_name"></el-input>
		    </el-form-item>
		    <!-- 价格 -->
		    <el-form-item label="价格" prop="goods_price">
		      <el-input v-model="editForm.goods_price" type="number"></el-input>
		   </el-form-item>
				<el-form-item label="销售价格" prop="goods_msg_price">
				  <el-input v-model="editForm.goods_msg_price" type="number"></el-input>
				</el-form-item>
				<el-form-item label="重量" prop="goods_weight">
				  <el-input v-model="editForm.goods_weight" type="number"></el-input>
				</el-form-item>
				<el-form-item label="是否推荐" prop="is_recommend">
					<!-- 是否推荐 -->
					<el-radio-group v-model="editForm.is_recommend" size="small">
					  <el-radio :label="true" border>是</el-radio>
					  <el-radio :label="false" border>否</el-radio>
					</el-radio-group>
				</el-form-item>
		  </el-form>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="editDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="editUserInfo">确 定</el-button>
		  </span>
		</el-dialog>
		
		
  </div>
</template>

<script>
export default {
  data () {
		// 验证价格的规则
		var checkPrice = (rule, value, callback) => {
			// 验证价格
			if (value >= 0) {
				return callback()
			}
			callback(new Error('数值不能小于0'))
		}
    return {
			api_url: this.$api_url,
			api_upload: this.$api_upload,
      // 获取商品列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 10,
				// 店铺id
				_id: '',
      },
      total: 0,
      goodsList: [],
			// 控制修改商品对话框的显示和隐藏
			editDialogVisible: false,
			// 查询到的商品信息对象
			editForm: {},
			editFormRules: {
				goods_imgs: [{
				  required: true,
				  message: '请选择图片',
				  trigger: 'blur'
				}],
				goods_name: [{
				  required: true,
				  message: '请输入商品名称',
				  trigger: 'blur'
				},
				{
				  min: 10,
				  max: 100,
				  message: '商品名称的长度在 10 到 100 个字符',
				  trigger: 'blur'
				}],
				goods_price: [{
				  required: true,
				  message: '请输入价格',
				  trigger: 'blur'
				},
				{
				  validator: checkPrice,
				  trigger: 'blur'
				}],
				goods_msg_price: [{
				  required: true,
				  message: '请输入销售价格',
				  trigger: 'blur'
				},
				{
				  validator: checkPrice,
				  trigger: 'blur'
				}],
				goods_weight: [{
				  required: true,
				  message: '请输入商品重量',
				  trigger: 'blur'
				},
				{
				  validator: checkPrice,
				  trigger: 'blur'
				}]
			},
			fileList: [],
			userinfo:{}
    }
  },
  created () {
		this.userinfo = JSON.parse(window.sessionStorage.getItem('userinfo'));
		if (JSON.parse(window.sessionStorage.getItem('storeinfo'))) {
			this.queryInfo._id = JSON.parse(window.sessionStorage.getItem('storeinfo'))._id;
		}
    // 获取所有商品列表
    this.getGoodsList()
  },
  methods: {
		handleRemove(file, fileList) {
		  console.log('remove',file);
			let filePath;
			if (file.response) {
				// 1.获取将要删除的图片的临时路径
				filePath = file.response[0].file;
			} else {
				// 1.获取将要删除的图片的临时路径
				filePath = file.url.split(this.api_url)[1];
			}
			// 2.从pics数组中,找到这图片对应的索引值
			const index = this.editForm.goods_imgs.findIndex(x => x === filePath);
			// 3.调用数组的splice方法,把图片信息对象从pics数组中移除
			this.editForm.goods_imgs.splice(index, 1)
			console.log('img',this.editForm.goods_imgs)
		},
		handlePreview(file) {
		  console.log('prev',file);
		},
		handleAvatarSuccess(res,file) {
			console.log('success',res,file);
			this.editForm.goods_imgs.push(file.response[0].file);
			console.log(this.editForm);
		},
    // 根据分页获取对应的商品列表
    async getGoodsList () {
			console.log('_id',this.queryInfo._id)
      const { data: res } = await this.$http.get('goods', {
        params: this.queryInfo
      })
			console.log(res);
      if (res.code !== 200) return this.$message.error(res.msg)
      this.$message.success(res.msg)
      this.goodsList = res.data.data;
      this.total = res.data.total;
      // console.log(res.goodsList)
    },
    // 监听pagesize改变的事件
    handleSizeChange (newSize) {
      // console.log('pagesize:' + newSize)
      this.queryInfo.pagesize = newSize
      this.getGoodsList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newPage) {
      // console.log('pagenum:' + newPage)
      this.queryInfo.pagenum = newPage
      this.getGoodsList()
    },
    // 删除商品
    async removeById (id) {
			console.log(id);
      const confirmResult = await this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }

      const { data: res } = await this.$http.delete('goods/' + id)
      if (res.code !== 200) {
        return this.$message.error(res.msg)
      }
      this.$message.success(res.msg)
      this.getGoodsList()
    },
    // 添加商品
    goAddpage () {
      this.$router.push('/goods/add')
    },
		// 展示编辑用户的对话框
		async showEditDialog (id) {
		  const { data: res } = await this.$http.get('goods/' + id)
			console.log(res);
		  if (res.code !== 200) return this.$message.error(res.msg)
			delete res.data.goods_dy_attr;
			delete res.data.goods_static_attr;
		  this.editForm = res.data;
			this.editForm.goods_imgs.forEach((item)=>{
				this.fileList.push({
					url: this.api_url + item
				})
			})
			console.log('list',this.editForm);
		  this.editDialogVisible = true
		},
		// 监听修改用户对话框的关闭事件
		editDialogClose () {
		  this.$refs.editFormRef.resetFields()
			this.fileList = [];
		},
		// 修改用户信息并提交
		editUserInfo () {
			console.log(this.editForm);
		  this.$refs.editFormRef.validate(async valid => {
		    if (!valid) return
		    // 发起修改用户信息的数据请求
		    const { data: res } = await this.$http.put('goods', this.editForm)
				console.log(res);
		    if (res.code !== 200) return this.$message.error(res.msg)
		    // 关闭对话框
		    this.editDialogVisible = false
				this.$message.success(res.msg)
		    // 刷新数据列表
		    this.getGoodsList()
		    // 提示修改成功
		    
		  })
		},
  }
}
</script>

<style lang="less" scoped>
	/deep/ .avatar-uploader .el-upload {
	    border: 1px dashed #d9d9d9;
	    border-radius: 6px;
	    cursor: pointer;
	    // position: relative;
	    overflow: hidden;
	  }
		.avatar-uploader {
			width: 90px;
			// display: block;
		}
	  .avatar-uploader .el-upload:hover {
	    border-color: #409EFF;
	  }
	  .avatar-uploader-icon {
	    font-size: 28px;
	    color: #8c939d;
	    width: 60px;
	    height: 60px;
	    line-height: 60px;
	    text-align: center;
	  }
	  .avatar {
	    width: 80px;
	    // height: 60px;
			margin-right: 10px;
	    // display: block;
	  }
		/deep/ .el-form-item__content {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			box-sizing: border-box;
		}
		/deep/ .el-upload-list__item {
			width: 100px; 
			float: left;
			margin-right: 10px;
		}
</style>
